#============================================================
#	Progress Array
#============================================================
# @datetime: 2022-3-6 10:36:14
#============================================================
tool
class_name ProgressArray
extends HBoxContainer


const ITEM = preload("Item.tscn")


export var texture : Texture setget set_texture
export var texture_size : Vector2 = Vector2(40, 40) setget set_texture_size 
export var value : float = 2 setget set_value


#============================================================
#   Set/Get
#============================================================
func set_texture(value: Texture) -> void:
	texture = value
	if not is_inside_tree():
		yield(self, "ready")
	for child in get_children():
		if child is TextureProgress:
			child.texture_progress = texture

func set_value(_value: float) -> void:
	value = _value
	__update_item__()

func set_texture_size(value: Vector2) -> void:
	texture_size = value
	__update_item__()


#============================================================
#   自定义
#============================================================
func __update_item__():
	if value < 0:
		return
	if not is_inside_tree():
		yield(self, "ready")
	var count = int(value)
	var latest = value - int(value)
	if latest > 0:
		count += 1
	# 节点不够则添加
	for i in (count - get_child_count()):
		var item = ITEM.instance()
		item.texture_progress = texture
		add_child(item)
	# 超出时隐藏之后的节点
	for i in range(count, get_child_count()):
		get_child(i).visible = false
	
	# 设置显示的值
	for i in count:
		__item_property__(get_child(i), 1)
	# 设置最后一个显示的值
	if latest > 0:
		__item_property__(get_child(count - 1), latest)


func __item_property__(item: TextureProgress, value_: float):
	item.texture_progress = texture
	item.rect_min_size = texture_size
	item.visible = true
	item.value = value_


